import React, {useImperativeHandle, useRef, useState} from 'react';
import {
    FinishBar,
    ProgressBarContainer,
    Slider,
    VoiceControlContainer,
    VoiceControlWrapper, VolumeProgress
} from "../style/VoiceControl.css";

function VoiceControl(props,myRef) {
    let _drag = false;
    let _dragProgress = 0;
    let [drag,setDrag] = useState(false);
    let progressRef = useRef()
    // useImperativeHandle()
    return (
        <VoiceControlContainer ref={myRef} className={props.show?"":"displayNone"}>
            <VoiceControlWrapper>
                <ProgressBarContainer ref={progressRef} onMouseDown={(e)=>mouseDownHandle(e)}>
                    <FinishBar progress={props.volume()}/>
                    <Slider progress={props.volume()}/>
                </ProgressBarContainer>
                <VolumeProgress>{Math.floor(props.volume()*100)+"%"}</VolumeProgress>
            </VoiceControlWrapper>
        </VoiceControlContainer>
    )


    function refreshDragProgress(e){
        let {top, bottom} = progressRef.current?.getBoundingClientRect()
        let cursorY = e.clientY
        let p;
        if (cursorY > bottom) p = 0;
        else if (top > cursorY) p = 1;
        else p = (bottom-cursorY) / (bottom-top)
        _dragProgress = p;
    }

    function mouseDownHandle(e){
        _drag = true;
        setDrag(_drag)
        refreshDragProgress(e);
        document.addEventListener("mousemove",mouseMoveHandle)
        document.addEventListener("mouseup",mouseUpHandle)

    }
    function mouseUpHandle(e){
        _drag = false;
        setDrag(_drag);
        refreshDragProgress(e)
        props.setVolume(_dragProgress);
        document.removeEventListener("mousemove",mouseMoveHandle)
        document.removeEventListener("mouseup",mouseUpHandle)
    }
    function mouseMoveHandle(e){
        if(_drag) {
            refreshDragProgress(e)
            props.setVolume(_dragProgress);
        }
    }
}


export default  React.forwardRef(VoiceControl);